package com.jichaoyun.common.utils;

import com.jichaoyun.common.model.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
public class FileUtil {

    public FileInfo upload(MultipartFile file,String uploadPath){
        String fileName = file.getOriginalFilename();
        //获取文件后缀名
        String suffix = file.getOriginalFilename().substring(fileName.lastIndexOf("."));
        String visibleUri = "/dg_files/" + fileName;
        String saveUri = uploadPath + '/' + fileName;
        Long fileSize = file.getSize();
        File saveFile = new File(saveUri);
        FileInfo info = new FileInfo();
        info.setFileName(fileName);
        info.setSuffix(suffix);
        info.setVisableUri(visibleUri);
        info.setSavePath(saveUri);
        info.setSize(fileSize);
        //这里判断的是文件路径+文件名的组合的路径是否存在，
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }else{
            return null;
        }
        try {
            file.transferTo(saveFile);  //保存文件到真实存储路径下
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info;
    }

    public Boolean deleteFile(String filePath){
        File file = new File(filePath);
        return file.delete();
    }

}
